import time
from device import Device

class DeviceManager:
    def __init__(self):
        """
        纯粹的设备管理器，不依赖任何云平台特定逻辑
        """
        self.devices = {}  # 存储所有注册的设备
        self.device_state = {
            "online": True,
            "last_update": time.time()
        }
        
    def register_device(self, device: Device):
        """注册新设备"""
        if not isinstance(device, Device):
            raise TypeError("device必须是Device的实例")
            
        if device.name in self.devices:
            print(f"警告: 设备 {device.name} 已经注册")
            return False
            
        # 初始化设备
        if device.initialize():
            self.devices[device.name] = device
            print(f"设备 {device.name} 注册成功")
            return True
        else:
            print(f"设备 {device.name} 初始化失败")
            return False
    
    def read_all_devices(self):
        """
        读取所有设备数据（保持原始格式）
        返回一个字典，键为设备名，值为设备数据
        """
        devices_data = {}
        timestamp = int(time.time())
        
        for name, device in self.devices.items():
            try:
                data = device.read_data()
                if data is not None:
                    devices_data[name] = data
            except Exception as e:
                print(f"读取设备 {name} 数据错误: {e}")
        
        self.device_state["last_update"] = timestamp
        return devices_data
    
    def execute_command(self, device_name, command, value=None):
        """
        在指定设备上执行命令
        """
        if device_name not in self.devices:
            return {"status": "error", "message": f"设备 {device_name} 未注册"}
            
        device = self.devices[device_name]
        try:
            result = device.execute_command(command, value)
            return result
        except Exception as e:
            print(f"执行设备 {device_name} 命令错误: {e}")
            return {"status": "error", "message": str(e)}
    
    def get_devices_list(self):
        """
        获取已注册设备列表
        """
        return list(self.devices.keys())